<template>
  <div class="department-detail-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">{{ isSelectMode ? '选择付款对象' : currentDepartment.name }}</div>
      </div>

      <!-- 搜索框 -->
      <div class="search-container">
        <van-search
          autocomplete="off"
          v-model="searchValue"
          placeholder="搜索"
          shape="round"
          background="transparent"
          left-icon="search"
          @search="onSearch"
          @focus="onSearchFocus"
        />
      </div>
    </div>

    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span class="breadcrumb-item clickable" @click="goToRoot">{{
        rootDepartment.name
      }}</span>
      <van-icon name="arrow" class="breadcrumb-arrow" />
      <span class="breadcrumb-item current">{{ currentDepartment.name }}</span>
    </div>

    <!-- 成员列表 -->
    <!-- 加载骨架屏 -->
    <div v-if="loading" class="org-skeleton">
      <van-skeleton :row="6" :loading="true" />
    </div>

    <!-- 未设置主管提示 -->
    <div
      v-if="!loading && !hasManager && members.length > 0 &&isAdmin"
      class="no-manager-tip"
      @click.stop="setManager"
    >
      <div class="tip-icon">
        <!-- <van-icon name="manager" /> -->
        <img
          class="tip-icon-img"
          src="/src/assets/homeOther/user_icon.png"
          alt=""
        />
      </div>
      <div class="tip-text">
        <div class="tip-title">未设置主管</div>
        <div class="tip-desc">主管可以进行部门内人员管理</div>
      </div>
      <van-icon name="arrow" class="arrow-icon" />
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && members.length === 0" class="empty-container">
      <img
        src="/src/assets/homeOther/empty.png"
        alt="暂无数据"
        class="empty-image"
      />
    </div>

    <div class="member-list" v-if="!loading && members && members.length > 0">
      <!-- 部门成员 -->
      <div
        v-for="member in members"
        :key="member.id"
        class="member-item"
        @click="isSelectMode ? selectUser(member) : editMember(member)"
        :class="{ 'selectable': isSelectMode }"
      >
        <div class="member-avatar">
          <AvatarDisplay :url="member.url" :name="member.name" />
        </div>
        <div class="member-info">
          <div class="member-name">
            {{ member.name }}
            <span v-if="member.isManager" class="manager-tag">主管</span>
          </div>
          <div class="member-position">{{ member.position }}</div>
        </div>
        <!-- <van-icon name="edit" class="edit-icon" /> -->
        <img
          v-if="!isSelectMode"
          src="/src/assets/homeOther/edit_icon.png"
          class="edit-icon"
          alt=""
          @click="editMember(member)"
        />
      </div>
    </div>

    <!-- 底部操作按钮 - 仅管理员可见且非选择模式 -->
    <div v-if="isAdmin && !isSelectMode" class="bottom-actions">
      <div class="action-buttons">
        <div class="action-btn" @click="addMember">
          <span>添加成员</span>
        </div>
        <div class="action-btn" @click="addSubDepartment">
          <span>部门管理</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import { findDepartmentById, getDepartmentDetail, type DepartmentMember } from "@/api/organization";
import { getUserById } from "@/api/user";
import { storage } from '@/utils/storage';
import { smartGoBack } from '@/utils/navigation';
import AvatarDisplay from "@/components/UserAvatar/AvatarDisplay.vue";
import { getUserPicture } from "@/api/contract";
import defaultAvatar from "@/assets/homeOther/picture.png";

// 路由实例
const router = useRouter();
const route = useRoute();

// 是否为选择模式（从付款对象页面跳转过来）
const isSelectMode = computed(() => route.query.mode === 'select');
const selectSource = computed(() => route.query.from as string);

// 搜索值
const searchValue = ref("");

// 成员数据类型（适配前端显示需求）
interface Member {
  id: number;
  name: string;
  position: string;
  avatar: string;
  url: string; // 添加url字段用于头像组件
  isManager: boolean;
  departmentId: string;
}

// 部门数据类型
interface Department {
  id: string;
  name: string;
  description: string;
  memberCount: number;
  parentId?: string;
}

// 根部门
const rootDepartment = reactive({
  id: "root",
  name: "北京君初律师事务所",
});

// 当前部门 - 根据路由参数获取
const currentDepartment = reactive({
  id: "",
  name: "",
});

// 部门成员数据
const members = ref<Member[]>([]);

// 加载状态
const loading = ref(false); // 初始为false，避免闪烁

// 当前登录用户信息
const currentUser = ref<any>(null);
// 当前用户详细信息（从接口获取）
const currentUserDetail = ref<any>(null);

// 计算属性：判断当前用户是否为管理员
const isAdmin = computed(() => {
  return currentUserDetail.value?.admin === 1;
});

// 获取用户头像（基于后端头像接口）
const getUserAvatar = async (url: string): Promise<string> => {
  if (!url || url.trim() === "") {
    return defaultAvatar;
  }

  try {
    const avatarBlob = await getUserPicture(url);
    return URL.createObjectURL(avatarBlob);
  } catch (error) {
    console.error("获取用户头像失败:", error);
    return defaultAvatar;
  }
};

// 获取部门详情（包含部门名称）
const fetchDepartmentDetail = async () => {
  try {
    const departmentId = route.params.id as string;
    const departmentName = route.query.departmentName as string;

    // 优先使用路由查询参数中的部门名称
    if (departmentName) {
      currentDepartment.id = departmentId;
      currentDepartment.name = departmentName;
      console.log("使用路由参数中的部门名称:", departmentName);
      return;
    }

    // 如果没有路由参数，则调用API获取部门详情
    const response = await getDepartmentDetail(departmentId);

    if (response.code === 0) {
      // 设置真实的部门名称
      currentDepartment.id = departmentId;
      currentDepartment.name = response.data.name;
      console.log("部门详情获取成功:", response.data);
    } else {
      // 如果获取失败，使用临时名称
      currentDepartment.name = `部门${departmentId}`;
      console.warn("获取部门详情失败，使用临时名称");
    }
  } catch (error) {
    console.error("获取部门详情失败:", error);
    // 如果获取失败，使用临时名称
    const departmentId = route.params.id as string;
    currentDepartment.name = `部门${departmentId}`;
  }
};

// 获取部门成员数据
const fetchDepartmentMembers = async () => {
  try {
    loading.value = true;
    const departmentId = route.params.id as string;
    const response = await findDepartmentById(departmentId);

    if (response.code === 0) {
      // 处理成员数据，获取头像
      const membersWithAvatars = await Promise.all(
        response.data.map(async (member: DepartmentMember) => {
          const avatar = await getUserAvatar(member.url);
          return {
            id: member.id,
            name: member.name,
            // position: member.isLeader ? '主管' : '成员',
            position: member.position,
            avatar: avatar,
            url: member.url, // 保留原始url用于头像组件
            isManager: member.isLeader,
            departmentId: departmentId,
          };
        })
      );

      members.value = membersWithAvatars;
      console.log("部门成员数据加载成功:", response.data);
    } else {
      showToast(response.msg || "获取部门成员失败");
    }
  } catch (error) {
    console.error("获取部门成员失败:", error);
    showToast("获取部门成员失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 获取当前登录用户信息
const getCurrentUserInfo = async () => {
  try {
    const userInfo = storage.getUserInfo();
    if (userInfo) {
      currentUser.value = userInfo;
      console.log("当前用户信息:", userInfo);
      
      // 调用接口获取用户详细信息
      const response = await getUserById(userInfo.id.toString());
      if (response.code === 0) {
        currentUserDetail.value = response.data;
        console.log("用户详细信息:", response.data);
        console.log("是否为管理员:", response.data.admin === 1);
      }
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 计算是否有主管
const hasManager = computed(() => {
  return members.value.some((member) => member.isManager);
});

// 返回上一页
const goBack = () => {
  smartGoBack(router);
};

// 返回根部门（组织架构首页）
const goToRoot = () => {
  router.push("/organization");
};

// 搜索功能
const onSearch = (value: string) => {
  // 跳转到搜索页面，传递搜索关键词
  router.push({
    path: "/organization/search",
    query: {
      keyword: value,
    },
  });
};

// 搜索框获取焦点事件
const onSearchFocus = () => {
  // 跳转到搜索页面
  router.push("/organization/search");
};

// 查看成员详情
const viewMemberDetail = (member: Member) => {
  showToast(`查看${member.name}的详情`);
};

// 添加成员
const addMember = () => {
  const departmentId = route.params.id as string;
  router.push(
    `/organization/add-member?from=department&departmentId=${departmentId}`
  );
};

// 部门管理（编辑部门）
const addSubDepartment = () => {
  const departmentId = route.params.id as string;
  router.push(
    `/organization/add-department?from=department&parentId=${departmentId}&mode=edit`
  );
};

// 设置部门主管
const setManager = () => {
  const departmentId = route.params.id as string;
  console.log("设置主管 - 部门ID:", departmentId);
  if (!departmentId) {
    showToast("部门ID获取失败");
    return;
  }
  router.push(`/organization/set-manager?departmentId=${departmentId}`);
};

// 初始化部门信息
const initDepartment = async () => {
  const departmentId = route.params.id as string;

  // 设置当前部门ID
  currentDepartment.id = departmentId;

  // 获取部门详情（包含真实名称）
  await fetchDepartmentDetail();
};
// 选择用户（选择模式下使用）
const selectUser = (member: Member) => {
  if (!isSelectMode.value) return;
  
  // 根据来源页面返回不同的路径
  if (selectSource.value === 'payObject') {
    // 返回付款申请页面，携带选中的用户信息
    router.push({
      path: '/contract/addPay',
      query: {
        selectedUserId: member.id.toString(),
        selectedUserName: member.name
      }
    });
  }
};

// 编辑成员
const editMember = (member: Member) => {
  router.push(`/organization/edit-member/${member.id}`);
};
// 页面加载
onMounted(async () => {
  console.log("部门详情页面已加载");
  
  // 优化加载体验：延迟显示loading，避免闪烁
  let loadingTimer: NodeJS.Timeout | null = null;
  
  // 延迟显示loading，避免闪烁
  loadingTimer = setTimeout(() => {
    loading.value = true;
  }, 200);
  
  try {
    await getCurrentUserInfo(); // 获取当前用户信息
    await initDepartment();
    fetchDepartmentMembers();
  } finally {
    // 数据加载完成后清除定时器和loading状态
    if (loadingTimer) {
      clearTimeout(loadingTimer);
      loadingTimer = null;
    }
    loading.value = false;
  }
});
</script>

<style lang="scss" scoped>
@import url("./style/department.scss");

/* 选择模式下的样式 */
.selectable {
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: rgba(25, 137, 250, 0.05);
  }
  
  &:active {
    background-color: rgba(25, 137, 250, 0.1);
  }
}
</style>